package org.dtp.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;
import java.util.Map;

/**
 * @ClassName JsonUtils
 * @Description json转换工具类
 * @Author wangyiqi
 * @Date 2021-08-15-12:26
 **/
public class JsonUtil {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 对象转换Map
     *
     * @param object 转换对象
     * @param clazz  目标类型
     * @return 转换结果
     */
    public static Map<String, Object> objectParseMap(Object object, Class clazz) {
        try {
            String json = MAPPER.writeValueAsString(object);
            JavaType javaType = getCollectionType(clazz, String.class, Object.class);
            return MAPPER.readValue(json, javaType);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("[" + object + "] transform [" + clazz + "] exception", e);
        }
    }


    /**
     * 对象转换List
     *
     * @param object 转换对象
     * @param clazz  目标类型
     * @param type   类型
     * @param <T>    /
     * @return
     */
    public static <T> List<T> objectParseList(Object object, Class clazz, Class<T> type) {
        try {
            String json = MAPPER.writeValueAsString(object);
            JavaType javaType = getCollectionType(clazz, type);
            return MAPPER.readValue(json, javaType);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("[" + object + "] transform [" + clazz + "] exception", e);
        }
    }

    /**
     * 获取泛型的Collection Type
     *
     * @param collectionClass 泛型的Collection
     * @param elementClasses  元素类
     */
    private static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return MAPPER.getTypeFactory().constructParametricType(collectionClass, elementClasses);

    }

}